#include "md5rc4.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include <QByteArray>
#include <QCryptographicHash>


Md5Rc4::Md5Rc4()
{

}



//md5加密
QString Md5Rc4::md5Encryption(QString input)
{
    QString result;

    QByteArray bb,cc;
    cc=input.toLatin1();
    bb=QCryptographicHash::hash(cc,QCryptographicHash::Md5);
    result=bb.toHex();//转换存储方式

    qDebug()<<"md5="<<result;
    return result;
}

//用rc4加密解密
void Md5Rc4::rc4EncryptionDecode(char *pData, unsigned long len)
{
    unsigned char s[1024] = { 0 };
    char key[256] = { 0 };

    if(key_.isEmpty())
    {
        memcpy(key,"xinruiforGD",strlen("xinruiforGD"));
    }
    else
    {
        QByteArray st_buf=key_.toUtf8();
        char* sTemp4 = st_buf.data();

        memcpy(key,sTemp4,strlen(sTemp4));
    }

    rc4_init(s, (unsigned char*)key, strlen(key));//初始化密钥

    rc4_crypt(s, (unsigned char*)pData, len);//解密
    qDebug()<<"加密，解密成功";
//    qDebug()<<"pData="<< pData;
}

/*rc4加解密*/
void Md5Rc4::rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len)
{
    int i = 0, j = 0, t = 0;
    unsigned long k = 0;
    unsigned char tmp;
    for (k = 0; k<Len; k++)
    {
        i = (i + 1) % 256;
        j = (j + s[i]) % 256;
        tmp = s[i];
        s[i] = s[j];//交换s[x]和s[y]
        s[j] = tmp;
        t = (s[i] + s[j]) % 256;
        Data[k] ^= s[t];
    }
}

/*初始化密匙函数*/
void Md5Rc4::rc4_init(unsigned char *s, unsigned char *key, unsigned long Len)
{
    int i = 0, j = 0;
    char k[257] = { 0 };
    unsigned char tmp = 0;
    for (i = 0; i<256; i++)
    {
        s[i] = i;
        k[i] = key[i%(Len)];
    }
    for (i = 0; i<256; i++)
    {
        j = (j + s[i] + k[i]) % 256;
        tmp = s[i];
        s[i] = s[j];//交换s[i]和s[j]
        s[j] = tmp;
        if(s[i]=='\0')
        {
//            qDebug()<<"i="<<i;
//            s[i]='a';
        }

        if(s[j]=='\0')
        {
//            qDebug()<<"j="<<j;
//            s[j]='a';
        }

    }
}
